package com.henghai.zhenxuan.ui.page.home;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;


import com.henghai.zhenxuan.BR;
import com.henghai.zhenxuan.data.bean.HttpBean;
import com.henghai.zhenxuan.data.bean.IssueTaskBean;
import com.henghai.zhenxuan.data.bean.NoticeBean;
import com.henghai.zhenxuan.data.bean.WinnerBean;
import com.henghai.zhenxuan.domain.event.Messages;
import com.henghai.zhenxuan.domain.message.PageMessenger;
import com.henghai.zhenxuan.domain.request.IssueTaskRequester;
import com.henghai.zhenxuan.domain.request.QueryNoticeRequester;
import com.henghai.zhenxuan.domain.request.WinningRequester;
import com.henghai.zhenxuan.ui.page.adapter.TaskListAdapter;
import com.henghai.zhenxuan.ui.page.login.LoginActivity;
import com.henghai.zhenxuan.utils.Utils;
import com.henghai.zhenxuan.R;
import com.kongzue.dialogx.dialogs.TipDialog;
import com.kongzue.dialogx.dialogs.WaitDialog;
import com.kunminx.architecture.ui.page.BaseFragment;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.page.StateHolder;
import com.kunminx.architecture.ui.state.State;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends BaseFragment {


    private HomeStates mStates;
    private TaskListAdapter mAdapter;
    private QueryNoticeRequester mQueryNoticeRequester;
    private IssueTaskRequester mIssueTaskRequester;

    private RefreshLayout mRefreshLayout;
    private PageMessenger mMessenger;
    private WinningRequester mWinningRequester;

    @Override
    protected void initViewModel() {
        mStates = getFragmentScopeViewModel(HomeStates.class);
        mQueryNoticeRequester = getFragmentScopeViewModel(QueryNoticeRequester.class);
        mIssueTaskRequester = getFragmentScopeViewModel(IssueTaskRequester.class);
        mWinningRequester = getFragmentScopeViewModel(WinningRequester.class);
        mMessenger = getApplicationScopeViewModel(PageMessenger.class);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mWinningRequester.getResult().observe(this, dataResult -> {
            if (!dataResult.getResponseStatus().isSuccess()) {
                return;
            }
            ArrayList<String> inForms = Utils.convertData(dataResult.getResult().getData().getRows());
            mStates.informList.set(inForms);
        });
        mWinningRequester.request(this);
        WaitDialog.show("正在加载").setOnBackPressedListener(waitDialog -> {
            waitDialog.doDismiss();
            return false;
        });
        mQueryNoticeRequester.getTokenResult().observe(this, httpBeanDataResult -> {
            if (!httpBeanDataResult.getResponseStatus().isSuccess()) {
                if (httpBeanDataResult.getResponseStatus().getResponseCode().equals(getString(com.henghai.zhenxuan.R.string.http_token_error))) {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                    getActivity().finish();
                }
                TipDialog.show(httpBeanDataResult.getResponseStatus().getResponseCode(), WaitDialog.TYPE.ERROR);
                return;
            }
            HttpBean<ArrayList<NoticeBean>> dataResult = httpBeanDataResult.getResult();
            if (!dataResult.getData().isEmpty()) {
                mStates.bannerList.set(dataResult.getData().get(0).getSysNoticeFileList());
            }
        });

        mIssueTaskRequester.getIssueTaskResult().observe(this, httpBeanDataResult -> {
            if (mRefreshLayout != null) {
                mRefreshLayout.finishRefresh();
                mRefreshLayout.finishLoadMore();
            }
            WaitDialog.dismiss();
            if (!httpBeanDataResult.getResponseStatus().isSuccess()) {
                TipDialog.show(httpBeanDataResult.getResponseStatus().getResponseCode(), WaitDialog.TYPE.ERROR);
                return;
            }
            mStates.rows = httpBeanDataResult.getResult().getData().getRows().size();
            List<IssueTaskBean.RowsBean> list = new ArrayList<>();
            list.addAll(mStates.taskList.get());
            list.addAll(httpBeanDataResult.getResult().getData().getRows());
            mStates.taskList.set(list);
        });

        mQueryNoticeRequester.requestQueryNotice(this);
        mIssueTaskRequester.requestIssueTask(this, mStates.pageNum + "", mStates.PageSize);

        mMessenger.output(this, messages -> {
            if (messages.eventId == Messages.EVENT_TASK_SUCCESS) {
                mIssueTaskRequester.requestIssueTask(this, mStates.pageNum + "", mStates.PageSize);
            }
        });
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        mAdapter = new TaskListAdapter(getContext());
        mAdapter.setOnItemClickListener((i, taskBean, i1) -> {
            Bundle bundle = new Bundle();
            bundle.putString("taskStatus", taskBean.getTaskStatus() + "");
            bundle.putString("taskId", taskBean.getId() + "");
//            nav().navigate(R.id.action_mainFragment_to_TaskFragment, bundle);
        });
        return new DataBindingConfig(R.layout.fragment_home, BR.vm, mStates)
                .addBindingParam(BR.listener, new ListenerRefreshHandler())
                .addBindingParam(BR.loadListener, new ListenerLoadHandler())
                .addBindingParam(BR.adapter, mAdapter).addBindingParam(BR.click, new ClickProxy());
    }

    public class ListenerLoadHandler implements OnLoadMoreListener {
        @Override
        public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
            mRefreshLayout = refreshLayout;
            if (mStates.rows >= Integer.parseInt(mStates.PageSize)) {
                mStates.pageNum++;
                mIssueTaskRequester.requestIssueTask(getViewLifecycleOwner(), mStates.pageNum + "", mStates.PageSize);
            } else {
                mRefreshLayout.finishLoadMoreWithNoMoreData();
            }
        }
    }

    public class ListenerRefreshHandler implements OnRefreshListener {
        @Override
        public void onRefresh(@NonNull RefreshLayout refreshLayout) {
            mStates.pageNum = 1;
            mStates.taskList.set(new ArrayList<>());
            mRefreshLayout = refreshLayout;
            mQueryNoticeRequester.requestQueryNotice(getViewLifecycleOwner());
            mIssueTaskRequester.requestIssueTask(getViewLifecycleOwner(), mStates.pageNum + "", mStates.PageSize);
        }
    }

    public class ClickProxy {
        public void noticeBoard() {
            nav().navigate(R.id.action_mainFragment_to_NoticeFragment);
        }
    }

    public static class HomeStates extends StateHolder {

        public int rows;
        public final String PageSize = "20";
        public int pageNum = 1;
        public final State<List<IssueTaskBean.RowsBean>> taskList = new State<>(new ArrayList<>());
        public final State<ArrayList<String>> informList = new State<>(new ArrayList<>());
        public final State<ArrayList<NoticeBean.NoticeFileBean>> bannerList = new State<>(new ArrayList<>());
        public final State<List<WinnerBean.RowsBean>> winnerList = new State<>(new ArrayList<>());


        public final State<String> url = new State<>("https://www.dxzy163.com/index.html");
    }
}
